import os
import tkinter as tk
import glob
import pdfplumber
import pyperclip

def pdf_extractor(pdf_file):
    
    pdf = pdfplumber.open(pdf_file)
    for page in pdf.pages:
        dot=0
        drug = {}
        result=[]
        copys=1
        lines = page.extract_table()
        for line in lines[1:-1]:
            dot += int(line[1].split('.')[0])
            drug[line[0].split('/')[0]]=line[1]
        if not dot%5:
            copys=5
        elif not dot%3:
            copys=3
        for k, v in drug.items():
            result.append(f"{k}{int(v.split('.')[0])//copys}g")
            
    return ' '.join(result)

class DrugInfo(tk.Tk):
    def __init__(self, drug_info):
        self.drug_info = drug_info
        super().__init__()
        self.wm_attributes('-topmost', 1)
        self.attributes('-alpha', 0.5)
        self.bind('<Enter>', self.show)
        self.bind('<Leave>', self.hide)
        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 800
        wh = 800
        self.geometry("%dx%d+%d+%d" % (ww, wh, (sw - ww)/1.2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.iconphoto(False, tk.PhotoImage(file='title.png'))
        self.title('中药信息')
        info_frame = tk.Frame(self)
        info_frame.pack()
        btn_split= tk.Button(info_frame,
                               text='分割',
                               command=self.split_it,
                               width=12,
                               height=1,
                               activebackground='grey',
                               relief='groove')
        btn_split.pack(side=tk.LEFT, padx=5)
        
        frash_btn = tk.Button(info_frame,
                              text='更新',
                              activebackground='grey',
                              width=12,
                              height=1,
                              relief='groove')
        frash_btn.bind('<ButtonRelease-1>', self.re_frash)
        frash_btn.pack(side=tk.LEFT, padx=5)
        btn_cancel = tk.Button(info_frame,
                               text='退出',
                               command=self.cancel,
                               width=12,
                               height=1,
                               activebackground='grey',
                               relief='groove')
        btn_cancel.pack(side=tk.LEFT, padx=5)
        self.radio_genarator()
        self.split_frame = tk.Frame(self)
        self.split_frame.pack()
        self.split_flag = True
        

    def radio_genarator(self):
        self.flag = tk.StringVar()
        self.flag.set('中药')
        self.radio_frame = tk.Frame(self)
        self.radio_frame.pack()
        
        for each_drug in self.drug_info:
            for k,v in each_drug.items():
                tk.Radiobutton(
                    self.radio_frame,
                    variable=self.flag,
                    text=f"{k}：{v}"[:80]+".." if len(f"{k}:{v}")>80 else f"{k}:{v}",
                    value=v,
                    command=self.on_select).pack(anchor=tk.W, padx=10)

        
    def show(self, event):
        self.attributes('-alpha', 1.0)
        self.update()

    def hide(self, event):
        self.attributes('-alpha', 0.5)
        self.update()

    def on_select(self):
        pyperclip.copy(self.flag.get())
        self.split_frame.destroy()
        self.split_frame = tk.Frame(self)
        self.split_frame.pack()
    def on_select_split(self):
        pyperclip.copy(self.split_text.get())

    def select_all(self, event):
        # event.widget 即触发事件的控件，可以直接用它的方法如.select_range()等
        event.widget.select_range(0, tk.END)

    def cancel(self):
        self.destroy()
    def split_it(self):
        if not self.split_flag:
            self.split_frame.destroy()
            self.split_frame = tk.Frame(self)
            self.split_frame.pack()
        text_ = self.flag.get().split()[::-1]
        self.split_text = tk.StringVar()
        self.split_text.set('split')
        
        text_list=[]
  
        text_to_split=[]
        
        while text_:
            x = text_.pop()
            text_to_split.append(x)
            if len(('*'+' '.join(text_to_split)).encode('gbk'))>44:
                text_to_split.pop()
                text_list.append(' '.join(text_to_split))
                
                text_to_split=[x, ]
                
                
            else:
                continue
                
        flag = True
        if len(('*'+' '.join(text_to_split)+" 水煎内服").encode('gbk'))<44:
            text_list.append(' '.join(text_to_split)+" 水煎内服")
            flag = False
        else:
            text_list.append(' '.join(text_to_split))   
        tk.Radiobutton(
                self.split_frame,
                variable=self.split_text,
                text='中药治疗',
                value='*中药治疗',
                command=self.on_select_split).pack(anchor=tk.W, padx=10)
        tk.Radiobutton(
                self.split_frame,
                variable=self.split_text,
                text='中药煎服 每日一付',
                value='*中药煎服 每日一付',
                command=self.on_select_split).pack(anchor=tk.W, padx=10)
                
        tk.Radiobutton(
                self.split_frame,
                variable=self.split_text,
                text='请中医儿科赵峥主任会诊',
                value='*请中医儿科赵峥主任会诊',
                command=self.on_select_split).pack(anchor=tk.W, padx=10)
        for each in text_list:
            
            tk.Radiobutton(
                self.split_frame,
                variable=self.split_text,
                text=each,
                value="*"+each,
                command=self.on_select_split).pack(anchor=tk.W, padx=10)
        if flag:    
            tk.Radiobutton(
                    self.split_frame,
                    variable=self.split_text,
                    text='水煎内服',
                    value='*水煎内服',
                    command=self.on_select_split).pack(anchor=tk.W, padx=10)
        self.split_flag = False
    def re_frash(self, event):
        
        self.state('icon')
        self.update()
        
        self.radio_frame.destroy()
        self.split_frame.forget()
        drug_list = []
        for each in glob.glob('E:\\RjDir\\ys\\Desktop\\pdf\\*.pdf'):
            drug_list.append({os.path.basename(each)[:-4]:pdf_extractor(each)})
        self.drug_info = drug_list
        self.radio_genarator()
        # event.widget.select_range(0, tk.END)
        self.update()
        self.state('normal')
        self.update()

if __name__== "__main__":
    drug_list = []
    for each in glob.glob('E:\\RjDir\\ys\\Desktop\\pdf\\*.pdf'):
        drug_list.append({os.path.basename(each)[:-4]:pdf_extractor(each)})
        
    app = DrugInfo(drug_list)
    app.mainloop()